package com.songshuang.myutilsboot.stlf.io;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public final class ModelFiles {
    private ModelFiles() {}

    public static List<String> scanModelVersions(double lng, double lat) {
        List<String> result = new ArrayList<>();
        try {
            File dir = new File(Constants.ANN_MODEL_PATH);
            if (!dir.exists() || !dir.isDirectory()) return result;
            String prefix = String.format("%.3f_%.3f", lng, lat);
            File[] files = dir.listFiles();
            if (files == null) return result;
            for (File f : files) {
                if (f.isFile()) {
                    String name = f.getName();
                    if (name.startsWith(prefix) && name.endsWith(".txt")) {
                        result.add(name.substring(0, name.length() - 4));
                    }
                }
            }
            Collections.sort(result);
        } catch (Exception ignored) {}
        return result;
    }

    public static List<String> scanModelVersions(double lng, double lat, String startDate, String endDate) {
        // 文件名中一般包含日期 _YYYYMMDD_，按该范围筛选
        List<String> all = scanModelVersions(lng, lat);
        if ((startDate == null || startDate.isEmpty()) && (endDate == null || endDate.isEmpty())) return all;
        List<String> filtered = new ArrayList<>();
        String sd = normalizeDate(startDate); // yyyyMMdd 或 null
        String ed = normalizeDate(endDate);
        for (String v : all) {
            String date = extractDateToken(v); // 从文件名提取类似 20240716
            if (date == null) continue;
            if ((sd == null || date.compareTo(sd) >= 0) && (ed == null || date.compareTo(ed) <= 0)) {
                filtered.add(v);
            }
        }
        return filtered;
    }

    private static String extractDateToken(String name) {
        // 例：116.595_40.080_20240716_v1.0 → 提取 20240716
        String[] p = name.split("_");
        for (String s : p) {
            if (s.matches("\\d{8}")) return s;
        }
        return null;
    }

    private static String normalizeDate(String d) {
        if (d == null || d.isEmpty()) return null;
        // 支持 yyyy-MM-dd / yyyyMMdd
        if (d.matches("\\d{8}")) return d;
        if (d.matches("\\d{4}-\\d{2}-\\d{2}")) return d.replace("-", "");
        return null;
    }
}


